package com.david.webtest.utils

import android.os.Environment
import android.os.Handler
import com.david.webtest.blog.BlogBean
import java.io.*

class BlogUtils {
    companion object {
        var handler: Handler = Handler()
        fun getBlog(onBlogRequestResponse: OnBlogRequestResponse) {
            val file = File((Environment.getExternalStorageDirectory()?.absolutePath ?: "") + "/blog/blogs.txt")
            if (!file.exists()) {
                onBlogRequestResponse.onBlogGetFail("文件不存在")
                return
            }
            Thread {
                kotlin.run {
                    val fileReader = FileReader(file)
                    val bufferedReader = BufferedReader(fileReader)
                    var line = bufferedReader.readLine()
                    val result:ArrayList<BlogBean> = ArrayList()
                    while (line != null) {
                        if (line.startsWith("http"))
                            result.add(BlogBean(PreferenceUtils.getInstance().getBlogName(line), line))
                        line = bufferedReader.readLine()
                    }

                    bufferedReader.close()
                    fileReader.close()

                    handler.post {
                        onBlogRequestResponse.onBlogRequested(result)
                    }
                }
            }.start()
        }

        fun addBlog(blogUrl:String, data:ArrayList<BlogBean>, onBlogAddListener:OnBlogAddListener){
            val file = File((Environment.getExternalStorageDirectory()?.absolutePath ?: "") + "/blog/blogs.txt")
            if (!file.exists()) {
                onBlogAddListener.onFail("文件不存在")
                return
            }

            Thread {
                kotlin.run {


                    val fileWriter = FileWriter(file)
                    val bufferWriter = BufferedWriter(fileWriter)


                    bufferWriter.write(blogUrl)
                    for ((index, item) in data.withIndex()) {
                        bufferWriter.write(item.url)
                    }

                    bufferWriter.close()
                    fileWriter.close()
                    handler.post {
                        onBlogAddListener.onBlogAdd(blogUrl)
                    }
                }
            }.start()
        }
    }

    abstract class OnBlogRequestResponse {
        abstract fun onBlogRequested(result:ArrayList<BlogBean>)
        abstract fun onBlogGetFail(msg: String)
    }

    interface OnBlogAddListener{
        fun onBlogAdd(blogUrl: String)
        fun onFail(errorMsg:String)
    }
}